/**
 *    Copyright ${license.git.copyrightYears} the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.executor.resultset;

import org.apache.ibatis.annotations.AutomapConstructor;
import org.apache.ibatis.binding.MapperMethod.ParamMap;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.cursor.defaults.DefaultCursor;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.executor.loader.ResultLoader;
import org.apache.ibatis.executor.loader.ResultLoaderMap;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.result.DefaultResultContext;
import org.apache.ibatis.executor.result.DefaultResultHandler;
import org.apache.ibatis.executor.result.ResultMapException;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.Discriminator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.reflection.MetaClass;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;

import java.lang.reflect.Constructor;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

/**
 * @author Clinton Begin
 * @author Eduardo Macarron
 * @author Iwao AVE!
 * @author Kazuki Shimizu
 */
public class DefaultResultSetHandler implements ResultSetHandler {

  private static final Object DEFERED = new Object();

  private final Executor executor;
  private final Configuration configuration;
  private final MappedStatement mappedStatement;
  private final RowBounds rowBounds;
  private final ParameterHandler parameterHandler;
  private final ResultHandler<?> resultHandler; //用户指定用于处理结果集 ResultHandler 对象
  private final BoundSql boundSql;
  private final TypeHandlerRegistry typeHandlerRegistry;
  private final ObjectFactory objectFactory; //对象工厂
  private final ReflectorFactory reflectorFactory; //反射工厂，生产Reflector对象

  // nested resultmaps nested内嵌
  private final Map<CacheKey, Object> nestedResultObjects = new HashMap<CacheKey, Object>();
  private final Map<String, Object> ancestorObjects = new HashMap<String, Object>();
  private Object previousRowValue;

  // multiple resultsets, key是resultSet的名称
  private final Map<String, ResultMapping> nextResultMaps = new HashMap<String, ResultMapping>();
  private final Map<CacheKey, List<PendingRelation>> pendingRelations = new HashMap<CacheKey, List<PendingRelation>>();

  // Cached Automappings
  private final Map<String, List<UnMappedColumnAutoMapping>> autoMappingsCache = new HashMap<String, List<UnMappedColumnAutoMapping>>();

  // temporary marking flag that indicate using constructor mapping (use field to reduce memory usage)
  private boolean useConstructorMappings;

  private final PrimitiveTypes primitiveTypes;

  private static class PendingRelation {
    public MetaObject metaObject;
    public ResultMapping propertyMapping;
  }

  private static class UnMappedColumnAutoMapping {
    private final String column;
    private final String property;
    private final TypeHandler<?> typeHandler;
    private final boolean primitive;

    public UnMappedColumnAutoMapping(String column, String property, TypeHandler<?> typeHandler, boolean primitive) {
      this.column = column;
      this.property = property;
      this.typeHandler = typeHandler;
      this.primitive = primitive;
    }
  }

  public DefaultResultSetHandler(Executor executor, MappedStatement mappedStatement, ParameterHandler parameterHandler, ResultHandler<?> resultHandler, BoundSql boundSql,
                                 RowBounds rowBounds) {
    this.executor = executor;
    this.configuration = mappedStatement.getConfiguration();
    this.mappedStatement = mappedStatement;
    this.rowBounds = rowBounds;
    this.parameterHandler = parameterHandler;
    this.boundSql = boundSql;
    this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
    this.objectFactory = configuration.getObjectFactory();
    this.reflectorFactory = configuration.getReflectorFactory();
    this.resultHandler = resultHandler;
    this.primitiveTypes = new PrimitiveTypes();
  }

  //
  // HANDLE OUTPUT PARAMETER
  //
  //对存储过程中输出参数的相关处理
  @Override
  public void handleOutputParameters(CallableStatement cs) throws SQLException {
    //获取用户传入的实际参数，并为其创建相应的 MetaObject 对象
    final Object parameterObject = parameterHandler.getParameterObject();
    final MetaObject metaParam = configuration.newMetaObject(parameterObject);
    //／获取 BoundSql.parameterMappings 集合， 其中记录了参数相关信息
    final List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    for (int i = 0; i < parameterMappings.size(); i++) { //遍历所有参数信息
      final ParameterMapping parameterMapping = parameterMappings.get(i);
      //如果存在输出类型的参数，则解析参数值，并设置到 parameterObject 中
      if (parameterMapping.getMode() == ParameterMode.OUT || parameterMapping.getMode() == ParameterMode.INOUT) {
        //／如果指定该输出参数为 ResultSet 类型，则需要进行映射
        if (ResultSet.class.equals(parameterMapping.getJavaType())) {
          handleRefCursorOutputParameter((ResultSet) cs.getObject(i + 1), parameterMapping, metaParam);
        } else {
          //使用 TypeHandler 获取参数值，并设置到 parameterObject 中
          final TypeHandler<?> typeHandler = parameterMapping.getTypeHandler();
          metaParam.setValue(parameterMapping.getProperty(), typeHandler.getResult(cs, i + 1));
        }
      }
    }
  }

  private void handleRefCursorOutputParameter(ResultSet rs, ParameterMapping parameterMapping, MetaObject metaParam) throws SQLException {
    if (rs == null) {
      return;
    }
    try {
      //获取映射使用的 ResultMap 对象
      final String resultMapId = parameterMapping.getResultMapId();
      final ResultMap resultMap = configuration.getResultMap(resultMapId);
      //／将结果集封装成 ResultSetWrapper 对象
      final ResultSetWrapper rsw = new ResultSetWrapper(rs, configuration);
      if (this.resultHandler == null) {
        //／创建用于保存映射结果对象的 DefaultResultHandler 对象
        final DefaultResultHandler resultHandler = new DefaultResultHandler(objectFactory);
        //／通过 handleRowValues 方法完成映射操作，并将结果对象保存到 DefaultResultHandler中
        handleRowValues(rsw, resultMap, resultHandler, new RowBounds(), null);
        //将映射得到的结果对象保存到 parameterObject 中
        metaParam.setValue(parameterMapping.getProperty(), resultHandler.getResultList());
      } else {
        handleRowValues(rsw, resultMap, resultHandler, new RowBounds(), null);
      }
    } finally {
      // issue #228 (close resultsets)
      closeResultSet(rs);
    }
  }


  /**
   * HANDLE RESULT SETS
   * 例如:
   * CREATE PROCEDURE test_proc_multi_result_set()
   * BEGIN
   *  select * from person;
   *  select * from item;
   * END;
   * @param stmt
   * @return
   * @throws SQLException
   */
  @Override
  public List<Object> handleResultSets(Statement stmt) throws SQLException {
    ErrorContext.instance().activity("handling results").object(mappedStatement.getId());

    //该集合用于保存映射结果集得到的结果对象
    final List<Object> multipleResults = new ArrayList<Object>();

    int resultSetCount = 0;
    // 获取第一个 ResultSet 对象，正如前面所说，可能存在多个 ResultSet ，这里只获取第一个 ResultSet
    ResultSetWrapper rsw = getFirstResultSet(stmt);

    //获取 MappedStatement resultMaps 集合，前面分析 MyBatis 初始化时介绍过 ，映射文件中的
    //resultMap 节点会被解析成 ResultMap 对象，保存到 MappedStatement.resultMaps 集合中
    //如果 SQL 节点能够产生多个 ResultSet ，那么我们可以在 SQL 节点的 resultMap 属性性中配置多个
    //<resultMap 节点的 id ，它们之间通过逗号分 隔，实现对多个结采集的映射
    List<ResultMap> resultMaps = mappedStatement.getResultMaps();

    int resultMapCount = resultMaps.size();
    //如果结果集不为空 ，则 ResultMaps 集合不能为空，否则抛出异常
    validateResultMapsCount(rsw, resultMapCount);
    // 遥历 resultMaps 集合
    while (rsw != null && resultMapCount > resultSetCount) {
      //获取该结果集对应的 ResultMap 对象
      ResultMap resultMap = resultMaps.get(resultSetCount);
      // 根据 ResultMap 定义的映射规则对 ResultSet 进行映射，并将映射的结果对象添加到 multipleResults 集合中保存
      handleResultSet(rsw, resultMap, multipleResults, null);
      // 获取下一个结果集
      rsw = getNextResultSet(stmt);
      // 清空 nestedResultObjects 集合，清空嵌套结果集
      cleanUpAfterHandlingResultSet();
      resultSetCount++;
    }

    // 获取 MappedStatement.resultSets 属性，该属性仅对多结果集的情况适用，
    // 该属性将列出语句执行后返回的结果集，并给每个结果集一个名称，名称是逗号分隔的
    // 这里会根据 ResultSet 的名称处理嵌套映射
    String[] resultSets = mappedStatement.getResultSets();
    if (resultSets != null) {
      while (rsw != null && resultSetCount < resultSets.length) {
        // 根据 resultSet 的名称，获取未处理的 ResultMapping
        ResultMapping parentMapping = nextResultMaps.get(resultSets[resultSetCount]);
        if (parentMapping != null) {
          //获取嵌套的ResultMap
          String nestedResultMapId = parentMapping.getNestedResultMapId();
          ResultMap resultMap = configuration.getResultMap(nestedResultMapId);
          // 根据 ResultMap 对象映射结果集
          handleResultSet(rsw, resultMap, null, parentMapping);
        }
        rsw = getNextResultSet(stmt); //获取下一个结采集
        cleanUpAfterHandlingResultSet(); //清空 nestedResultObjects 集合
        resultSetCount++;
      }
    }

    return collapseSingleResultList(multipleResults);
  }

  @Override
  public <E> Cursor<E> handleCursorResultSets(Statement stmt) throws SQLException {
    ErrorContext.instance().activity("handling cursor results").object(mappedStatement.getId());
    //获取结果集并封装成 ResultSetWrapper 对象
    ResultSetWrapper rsw = getFirstResultSet(stmt);
    //获取映射使用的 ResultMap 对象集合
    List<ResultMap> resultMaps = mappedStatement.getResultMaps();

    int resultMapCount = resultMaps.size();
    validateResultMapsCount(rsw, resultMapCount);
    if (resultMapCount != 1) { //边界检测，只能映射一个结果集
      throw new ExecutorException("Cursor results cannot be mapped to multiple resultMaps");
    }
    //使用第一个 ResultMap 对象
    ResultMap resultMap = resultMaps.get(0);
    //将 ResultSetWrapper 对象、映射使用的 ResultMap 对象以及控制映射的起止位置的 RowBounds对象封装成 DefaultCursor 对象
    return new DefaultCursor<E>(this, resultMap, rsw, rowBounds);
  }

  private ResultSetWrapper getFirstResultSet(Statement stmt) throws SQLException {
    ResultSet rs = stmt.getResultSet(); //获取 ResultSet 对象
    while (rs == null) {
      // move forward to get the first resultset in case the driver
      // doesn't return the resultset as the first result (HSQLDB 2.1)
      //检测是否还有待处理的 ResultSet
      if (stmt.getMoreResults()) {
        rs = stmt.getResultSet();
      } else {
        if (stmt.getUpdateCount() == -1) {
          // no more results. Must be no resultset
          //没有待处理的 ResultSet
          break;
        }
      }
    }
    //将结果集封装成 ResultSetWrapper 对象
    return rs != null ? new ResultSetWrapper(rs, configuration) : null;
  }

  private ResultSetWrapper getNextResultSet(Statement stmt) throws SQLException {
    // Making this method tolerant of bad JDBC drivers
    try {
      //检测 JDBC 是否支持多结果集
      if (stmt.getConnection().getMetaData().supportsMultipleResultSets()) {
        // Crazy Standard JDBC way of determining if there are more results
        //检测是否还有待处理的结果集，若存在， 则封装成 ResultSetWrapper 对象并返回
        if (!(!stmt.getMoreResults() && stmt.getUpdateCount() == -1)) {
          ResultSet rs = stmt.getResultSet();
          if (rs == null) {
            return getNextResultSet(stmt);
          } else {
            return new ResultSetWrapper(rs, configuration);
          }
        }
      }
    } catch (Exception e) {
      // Intentionally ignored.
    }
    return null;
  }

  private void closeResultSet(ResultSet rs) {
    try {
      if (rs != null) {
        rs.close();
      }
    } catch (SQLException e) {
      // ignore
    }
  }

  private void cleanUpAfterHandlingResultSet() {
    nestedResultObjects.clear();
  }

  private void validateResultMapsCount(ResultSetWrapper rsw, int resultMapCount) {
    if (rsw != null && resultMapCount < 1) {
      throw new ExecutorException("A query was run and no Result Maps were found for the Mapped Statement '" + mappedStatement.getId()
          + "'.  It's likely that neither a Result Type nor a Result Map was specified.");
    }
  }

  private void handleResultSet(ResultSetWrapper rsw, ResultMap resultMap, List<Object> multipleResults, ResultMapping parentMapping) throws SQLException {
    try {
      /**
       * 因为调用handleResultSet的只有handleResultSets，按说其中第一个调用永远不会出现parentMapping==null的情况，
       * 只有第二个调用才会出现这种情况，而且应该是连续的，因为第二个调用就是为了处理嵌套resultMap。
       * 所以在handleRowValues处理resultMap的时候，一定是主的先处理，嵌套的后处理，这样整个逻辑就比较清晰了。这里需要补个流程图。
       */
      // 处理嵌套/关联的resultMap(collection或association)
      if (parentMapping != null) {
        // 处理非主记录 resultHandler传递null，RowBounds传递默认值，parentMapping不为空
        handleRowValues(rsw, resultMap, null, RowBounds.DEFAULT, parentMapping);
      } else {
        //如果用户未指定处理映射结果对象 ResultHandler 对象, 则使用 DefaultResultHandler作为默认的 ResultHandler 对象
        if (resultHandler == null) {
          DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory);
          //对 ResultSet 进行映射，并将映射得到的结采对象添加到 DefaultResultHandler 对象中暂存
          handleRowValues(rsw, resultMap, defaultResultHandler, rowBounds, null);
          //将 DefaultResultHandler 中保存的结果对象添加到 multipleResults 集合中
          multipleResults.add(defaultResultHandler.getResultList());
        } else {
          handleRowValues(rsw, resultMap, resultHandler, rowBounds, null);
        }
      }
    } finally {
      // issue #228 (close resultsets)
      //调用 ResultSet.close 方法关闭结果集
      closeResultSet(rsw.getResultSet());
    }
  }

  @SuppressWarnings("unchecked")
  private List<Object> collapseSingleResultList(List<Object> multipleResults) {
    return multipleResults.size() == 1 ? (List<Object>) multipleResults.get(0) : multipleResults;
  }

  //
  // HANDLE ROWS FOR SIMPLE RESULTMAP
  //
  // 处理每一行记录,不管是主查询记录还是关联嵌套的查询结果集，他们的入参上通过resultHandler,rowBounds,parentMapping区分，具体见上述调用
  public void handleRowValues(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
    if (resultMap.hasNestedResultMaps()) { //针对存在嵌套 ResultMap 情况
      //检测是否允许在嵌套映射中使用 RowBound
      ensureNoRowBounds();
      //．检测是否允许在嵌套映射中使用用户自定义的 ResultHandler
      checkResultHandler();
      // 含有嵌套resultMap的列处理，通常是collection或者association
      handleRowValuesForNestedResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
    } else {
      //针对不含嵌套映射的简单映射的处理
      handleRowValuesForSimpleResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
    }
  }

  private void ensureNoRowBounds() {
    if (configuration.isSafeRowBoundsEnabled() && rowBounds != null && (rowBounds.getLimit() < RowBounds.NO_ROW_LIMIT || rowBounds.getOffset() > RowBounds.NO_ROW_OFFSET)) {
      throw new ExecutorException("Mapped Statements with nested result mappings cannot be safely constrained by RowBounds. "
          + "Use safeRowBoundsEnabled=false setting to bypass this check.");
    }
  }

  protected void checkResultHandler() {
    if (resultHandler != null && configuration.isSafeResultHandlerEnabled() && !mappedStatement.isResultOrdered()) {
      throw new ExecutorException("Mapped Statements with nested result mappings cannot be safely used with a custom ResultHandler. "
          + "Use safeResultHandlerEnabled=false setting to bypass this check "
          + "or ensure your statement returns ordered data and set resultOrdered=true on it.");
    }
  }

  /**
   * 主要步骤：
   * （1）调用skipRows（方法，根据RowBounds中的offset 值定位到指定的记录行。
   * （2）调用shouldProcessMoreRows（）方法，检测是否还有需要映射的记录。
   * （3）通过resolveDiscriminatedResultMap）方法，确定映射使用的ResultMap对象。
   * （4）调用getRowValue（）方法对ResultSet中的一行记录进行映射∶
   *    a）通过 createResultObject（）方法创建映射后的结果对象。
   *    b）通过 shouldApplyAutomaticMappings（）方法判断是否开启了自动映射功能。
   *    c）通过 applyAutomaticMappings（）方法自动映射ResultMap中未明确映射的列。
   *    d）通过 applyPropertyMappings（）方法映射ResultMap中明确映射列，到这里该行记录的数据已经完全映射到了结果对象的相应属性中。
   *（5）调用storeObject）方法保存映射得到的结果对象。
   * @param rsw
   * @param resultMap
   * @param resultHandler
   * @param rowBounds
   * @param parentMapping resolveDiscriminatedResultMap
   * @throws SQLException
   */
  private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping)
      throws SQLException {
    DefaultResultContext<Object> resultContext = new DefaultResultContext<Object>();
    // 设置从指定行开始,这是mybatis进行内部分页,不是依赖服务器端的分页实现
    //步骤 1：根据 RowBounds 中的 offset 定位到指定的记录
    skipRows(rsw.getResultSet(), rowBounds);
    // 确保没有超过mybatis逻辑分页限制,同时结果集中还有记录没有fetch
    //／步骤 2：检测已经处理的行数是否已经达到上眼（RowBounds.limit）以及 ResultSet 中是否还有可处理的记录
    while (shouldProcessMoreRows(resultContext, rowBounds) && rsw.getResultSet().next()) {
      // 解析鉴别器，得到嵌套的最深的鉴别器对应的ResultMap，如果没有鉴别器，就返回最顶层的ResultMap
      //步骤 3：根据该行记录以及 ResultMap.discriminator ，决定映射使用的 ResultMap
      ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rsw.getResultSet(), resultMap, null);
      // 这个时候resultMap是非常干净的,没有嵌套任何其他东西了，但是这也是最关键的地方，将ResultSet记录转换为业务层配置的对象类型或者Map类型
      //步骤 4：根据最终确定的 ResultMap对ResultSet 中的该行记录进行映射，得到映射后的结采对象
      Object rowValue = getRowValue(rsw, discriminatedResultMap);
      //步骤 5：将映射创建的结果对象添加到 ResultHandler.resultList 中保存
      storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
    }
  }

  private void storeObject(ResultHandler<?> resultHandler, DefaultResultContext<Object> resultContext, Object rowValue, ResultMapping parentMapping, ResultSet rs) throws SQLException {
    if (parentMapping != null) {
      // 嵌套查询或嵌套映射，将结果对象保存到父对象对应的属性中
      linkToParents(rs, parentMapping, rowValue);
    } else {
      // 普通映射，将结果对象保存到 ResultHandler 中
      callResultHandler(resultHandler, resultContext, rowValue);
    }
  }

  @SuppressWarnings("unchecked" /* because ResultHandler<?> is always ResultHandler<Object>*/)
  private void callResultHandler(ResultHandler<?> resultHandler, DefaultResultContext<Object> resultContext, Object rowValue) {
    //递增 DefaultResultContext.resultCount ，该值用于检测处理的记录行数是否已经达到上限（在 RowBounds.limit 字段中记录了该上限）
    resultContext.nextResultObject(rowValue);
    //将结果对象添加到 ResultHandler.resultList 中保存
    ((ResultHandler<Object>) resultHandler).handleResult(resultContext);
  }

  private boolean shouldProcessMoreRows(ResultContext<?> context, RowBounds rowBounds) throws SQLException {
    //一个是检测 DefaultResultContext.stopped 字段，另一个是检测映射行数是否达到了 RowBounds.limit 的限制
    return !context.isStopped() && context.getResultCount() < rowBounds.getLimit();
  }

  private void skipRows(ResultSet rs, RowBounds rowBounds) throws SQLException {
    //根据 ResultSet 的类型进行定位
    if (rs.getType() != ResultSet.TYPE_FORWARD_ONLY) {
      if (rowBounds.getOffset() != RowBounds.NO_ROW_OFFSET) {
        rs.absolute(rowBounds.getOffset()); //直接定位到 offset 指定的记录
      }
    } else {
      //通过多次调用 ResultSet.next （）方法移动到指定的记录
      for (int i = 0; i < rowBounds.getOffset(); i++) {
        rs.next();
      }
    }
  }

  //
  // GET VALUE FROM ROW FOR SIMPLE RESULT MAP
  //

  /**
   * 基本步骤:
   * （1）根据 ResultMap指定的类型创建对应的结果对象，以及对应的MetaObject对象。
   * （2）根据配置信息，决定是否自动映射ResultMap中未明确映射的列。
   * （3）根据ResultMap映射明确指定的属性和列。
   * （4）返回映射得到的结果对象。
   * @param rsw
   * @param resultMap
   * @return
   * @throws SQLException
   */
  private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap) throws SQLException {
    final ResultLoaderMap lazyLoader = new ResultLoaderMap();
    //步骤 1：创建该行记录映射之后得到的结果对象， 该结果对象的类型由＜resultMap＞节点的 type 属性指定
    Object rowValue = createResultObject(rsw, resultMap, lazyLoader, null);
    if (rowValue != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
      //创建上述结果对象相应的 MetaObject 对象
      final MetaObject metaObject = configuration.newMetaObject(rowValue);
      //成功映射任意属性，则 foundValues为true ；否则 foundValues 为 false
      boolean foundValues = this.useConstructorMappings;
      //检测是否需妥进行自动映射
      if (shouldApplyAutomaticMappings(resultMap, false)) {
        //步骤 2：自动映射 ResultMap 中未明确指定的列
        foundValues = applyAutomaticMappings(rsw, resultMap, metaObject, null) || foundValues;
      }
      //步骤 3：映射 ResultMap 中明确指定需要映射的列
      foundValues = applyPropertyMappings(rsw, resultMap, metaObject, lazyLoader, null) || foundValues;
      foundValues = lazyLoader.size() > 0 || foundValues;
      //步骤 4：如果没有成功映射任何属性，则根据 mybatis-config.xml 中的<returnInstanceForEmptyRow＞配置决定返回空的结果对象还是返回 null
      rowValue = foundValues || configuration.isReturnInstanceForEmptyRow() ? rowValue : null;
    }
    return rowValue;
  }

  private boolean shouldApplyAutomaticMappings(ResultMap resultMap, boolean isNested) {
    if (resultMap.getAutoMapping() != null) { //获取 ResultMap 中的 autoMapping 属性值
      return resultMap.getAutoMapping();
    } else {
      if (isNested) { //检测是否为嵌套查询或是嵌套映射
        return AutoMappingBehavior.FULL == configuration.getAutoMappingBehavior();
      } else {
        return AutoMappingBehavior.NONE != configuration.getAutoMappingBehavior();
      }
    }
  }

  //
  // PROPERTY MAPPINGS
  //

  /**
   * 方法处理 ResultMap 需要进行映射的列， 在该方法中涉及延迟加载、嵌套映射等内容
   * @param rsw
   * @param resultMap
   * @param metaObject
   * @param lazyLoader
   * @param columnPrefix
   * @return
   * @throws SQLException
   */
  private boolean applyPropertyMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, ResultLoaderMap lazyLoader, String columnPrefix)
      throws SQLException {
    //获取该 ResultMap 中明确需要进行映射的列名 集合
    final List<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix);
    boolean foundValues = false;
    //／获取 ResultMap.propertyResultMappings 集合，其中记录了映射使用的所有 ResultMapping 对象该集合的填充过程
    final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings();
    for (ResultMapping propertyMapping : propertyMappings) {
      String column = prependPrefix(propertyMapping.getColumn(), columnPrefix);
      if (propertyMapping.getNestedResultMapId() != null) {
        // the user added a column attribute to a nested result map, ignore it
        //该属性需要使用一个嵌套 resultMap 进行映射，忽略 column 属性
        column = null;
      }
      //下面的逻辑主要处理三种场景
      //场景 1：column 是 "{prop1=coll,prop2=co12}"这种形式的，一般与嵌套查询配合使用，
      //表示将 col 和 col2 的列位传递给 内层嵌套查询作为参数
      //场景 2：基本类型的属性映射
      //场景 3：多结果集的场景处理，该属性来自另一个结果集
      if (propertyMapping.isCompositeResult() //--场景1
          || (column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH))) //--场景2
          || propertyMapping.getResultSet() != null) { //--场景3
        //通过 getPropertyMappingValue 方法完成映射，并得到属性值
        Object value = getPropertyMappingValue(rsw.getResultSet(), metaObject, propertyMapping, lazyLoader, columnPrefix);
        // issue #541 make property optional
        //获取属性名称
        final String property = propertyMapping.getProperty();
        if (property == null) {
          continue;
        } else if (value == DEFERED) {
          // DEFERED 表示的是占位符对象
          foundValues = true;
          continue;
        }
        if (value != null) {
          foundValues = true;
        }
        if (value != null || (configuration.isCallSettersOnNulls() && !metaObject.getSetterType(property).isPrimitive())) {
          // gcode issue #377, call setter on nulls (value is not 'found')
          // 设置属性值
          metaObject.setValue(property, value);
        }
      }
    }
    return foundValues;
  }

  private Object getPropertyMappingValue(ResultSet rs, MetaObject metaResultObject, ResultMapping propertyMapping, ResultLoaderMap lazyLoader, String columnPrefix)
      throws SQLException {
    if (propertyMapping.getNestedQueryId() != null) { //嵌套查询
      //获取嵌套查询的结果对象
      return getNestedQueryMappingValue(rs, metaResultObject, propertyMapping, lazyLoader, columnPrefix);
    } else if (propertyMapping.getResultSet() != null) { //多结果集的处理
      addPendingChildRelation(rs, metaResultObject, propertyMapping);   // TODO is that OK?
      return DEFERED; //返回占位符对象
    } else {
      //获取 ResultMapping 中记录的 TypeHandler 对象
      final TypeHandler<?> typeHandler = propertyMapping.getTypeHandler();
      final String column = prependPrefix(propertyMapping.getColumn(), columnPrefix);
      //使用 TypeHandler 对象获取属性值
      return typeHandler.getResult(rs, column);
    }
  }

  private List<UnMappedColumnAutoMapping> createAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String columnPrefix) throws SQLException {
    final String mapKey = resultMap.getId() + ":" + columnPrefix; //自动映射的缓存 key
    List<UnMappedColumnAutoMapping> autoMapping = autoMappingsCache.get(mapKey);
    if (autoMapping == null) { // autoMappingsCache 缓存未命中
      autoMapping = new ArrayList<UnMappedColumnAutoMapping>();
      //／从 ResultSetWrapper 中获取未映射的列名集合
      final List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
      for (String columnName : unmappedColumnNames) {
        String propertyName = columnName;
        if (columnPrefix != null && !columnPrefix.isEmpty()) { //．如果列名以列前缀开头，
          // When columnPrefix is specified,
          // ignore columns without the prefix.
          //则属性名称为列名去除前缀删除的部分， 如果明确指定了列前缀列名但没有以列前级开头 则跳过该列处理后面的列
          if (columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
            propertyName = columnName.substring(columnPrefix.length());
          } else {
            continue;
          }
        }
        //在结果对象中查找指定的属性名
        final String property = metaObject.findProperty(propertyName, configuration.isMapUnderscoreToCamelCase());
        //／检测是否存在该属性的 setter 方法，注意：如果是 MapWrapper 直返 true
        if (property != null && metaObject.hasSetter(property)) {
          if (resultMap.getMappedProperties().contains(property)) {
            continue;
          }
          final Class<?> propertyType = metaObject.getSetterType(property);
          if (typeHandlerRegistry.hasTypeHandler(propertyType, rsw.getJdbcType(columnName))) {
            //查找对应的 TypeHandler 对象
            final TypeHandler<?> typeHandler = rsw.getTypeHandler(propertyType, columnName);
            //创建 UnMappedColumnAutoMapping 对象，并添加到 autoMapping 集合中
            autoMapping.add(new UnMappedColumnAutoMapping(columnName, property, typeHandler, propertyType.isPrimitive()));
          } else {
            configuration.getAutoMappingUnknownColumnBehavior()
                .doAction(mappedStatement, columnName, property, propertyType);
          }
        } else {
          configuration.getAutoMappingUnknownColumnBehavior()
              .doAction(mappedStatement, columnName, (property != null) ? property : propertyName, null);
        }
      }
      autoMappingsCache.put(mapKey, autoMapping);
    }
    return autoMapping;
  }

  private boolean applyAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String columnPrefix) throws SQLException {
    //获取 ResultSet 存在 ResultMap 没有明确映射的列所对应的 UnMappedColumnAutoMapping合，
    // 如果 ResultMap 中设置的 resultType 为 java.util.HashMap 的话，则全部的列都会在这里获取到
    List<UnMappedColumnAutoMapping> autoMapping = createAutomaticMappings(rsw, resultMap, metaObject, columnPrefix);
    boolean foundValues = false;
    if (!autoMapping.isEmpty()) {
      for (UnMappedColumnAutoMapping mapping : autoMapping) { //追历 autoMapping 集合
        //使用 TypeHandler 获取自动映射的列位
        final Object value = mapping.typeHandler.getResult(rsw.getResultSet(), mapping.column);
        if (value != null) {
          foundValues = true;
        }
        if (value != null || (configuration.isCallSettersOnNulls() && !mapping.primitive)) {
          // gcode issue #377, call setter on nulls (value is not 'found')
          //将自动映射的属性位设置到结采对象中
          metaObject.setValue(mapping.property, value);
        }
      }
    }
    return foundValues;
  }

  // MULTIPLE RESULT SETS
  // 非主记录需要连接到主记录,这里涉及到collection和association的resultMap实现
  private void linkToParents(ResultSet rs, ResultMapping parentMapping, Object rowValue) throws SQLException {
    CacheKey parentKey = createKeyForMultipleResults(rs, parentMapping, parentMapping.getColumn(), parentMapping.getForeignColumn());
    // 判断当前的主记录是否有待关联的子记录，是通过pendingRelationsMap进行维护的，pendingRelations是在addPendingChildRelation中添加主记录的
    List<PendingRelation> parents = pendingRelations.get(parentKey);
    if (parents != null) {
      for (PendingRelation parent : parents) { //遥历 PendingRelations 集合
        if (parent != null && rowValue != null) {
          //将当前记录的结果对象添加到外层对象的相应属性中
          linkObjects(parent.metaObject, parent.propertyMapping, rowValue);
        }
      }
    }
  }

  private void addPendingChildRelation(ResultSet rs, MetaObject metaResultObject, ResultMapping parentMapping) throws SQLException {
    //步骤 1: 为指定结果集创建 CacheKey 对象
    CacheKey cacheKey = createKeyForMultipleResults(rs, parentMapping, parentMapping.getColumn(), parentMapping.getColumn());
    //步骤 2: 创建 PendingRelation 对象
    PendingRelation deferLoad = new PendingRelation();
    deferLoad.metaObject = metaResultObject;
    deferLoad.propertyMapping = parentMapping;
    //步骤 3: 将 PendingRelation 对象添加到 pendingRelations 缓存
    List<PendingRelation> relations = pendingRelations.get(cacheKey);
    // issue #255
    if (relations == null) {
      relations = new ArrayList<DefaultResultSetHandler.PendingRelation>();
      pendingRelations.put(cacheKey, relations);
    }
    relations.add(deferLoad);
    //步骤 4: 在 nextResultMaps 集合记录指定属性对应的结果集名称以及对应的 ResultMapping 对象
    ResultMapping previous = nextResultMaps.get(parentMapping.getResultSet());
    if (previous == null) {
      nextResultMaps.put(parentMapping.getResultSet(), parentMapping);
    } else {
      if (!previous.equals(parentMapping)) {//如果同名的结果集对应不同的 ResultMapping, 抛出异常
        throw new ExecutorException("Two different properties are mapped to the same resultSet");
      }
    }
  }

  private CacheKey createKeyForMultipleResults(ResultSet rs, ResultMapping resultMapping, String names, String columns) throws SQLException {
    CacheKey cacheKey = new CacheKey();
    cacheKey.update(resultMapping);//添加 ResultMapping
    if (columns != null && names != null) {
      //按照逗号切分列名
      String[] columnsArray = columns.split(",");
      String[] namesArray = names.split(",");
      for (int i = 0; i < columnsArray.length; i++) {
        //查询该行记录对应列的位
        Object value = rs.getString(columnsArray[i]);
        if (value != null) {
          cacheKey.update(namesArray[i]);//添加列名和列位
          cacheKey.update(value);
        }
      }
    }
    return cacheKey;
  }

  //
  // INSTANTIATION & CONSTRUCTOR MAPPING
  //

  /**
   * 方法负责创建数据库记录映射得到的结果对象
   * 该方法会根据结果集的列数、 ResultMap.constructorResultMappings 集合等信息
   * 选择不同的方式创建结果对象，
   * @param rsw
   * @param resultMap
   * @param lazyLoader
   * @param columnPrefix
   * @return
   * @throws SQLException
   */
  private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException {
    this.useConstructorMappings = false; // reset previous mapping result  标识是否使用构造函数创建该结果对象
    //记录构造函数的参数类型
    final List<Class<?>> constructorArgTypes = new ArrayList<Class<?>>();
    //记录构造函数的实参
    final List<Object> constructorArgs = new ArrayList<Object>();
    //创建该行记录对应的结果对象，该方法是该步骤的核心
    Object resultObject = createResultObject(rsw, resultMap, constructorArgTypes, constructorArgs, columnPrefix);
    //如采包含嵌套查询，且配置了延迟加载，则创建代理对象，
    if (resultObject != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
      final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings();
      for (ResultMapping propertyMapping : propertyMappings) {
        // issue gcode #109 && issue #149
        //拥有嵌套查询，且开启了延迟加载，则创建代理对象，默认使用的是 JavassistProxyFactory
        if (propertyMapping.getNestedQueryId() != null && propertyMapping.isLazy()) {
          resultObject = configuration.getProxyFactory().createProxy(resultObject, lazyLoader, configuration, objectFactory, constructorArgTypes, constructorArgs);
          break;
        }
      }
    }
    //记录是否使用构造器创建对象
    this.useConstructorMappings = resultObject != null && !constructorArgTypes.isEmpty(); // set current mapping result
    return resultObject;
  }

  private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, List<Class<?>> constructorArgTypes, List<Object> constructorArgs, String columnPrefix)
      throws SQLException {
    //获 ResultMap 中记 type 属性 ，也就是该行记录最终映射成的结果对象类型
    final Class<?> resultType = resultMap.getType();
    //创建该类型对应的 MetaClass 对象
    final MetaClass metaType = MetaClass.forClass(resultType, reflectorFactory);
    //获取 ResultMap 中记录的 constructor 节点信息，如果该集合不为空，则可以通过该集合确定相应 Java 中的唯一构造函数
    final List<ResultMapping> constructorMappings = resultMap.getConstructorResultMappings();
    //创建结采对象分为下面 4种场景
    //1.结果集只有一列，且存在 typeHandler 对象可以将该列转换成 resultType 类型的值
    if (hasTypeHandlerForResultObject(rsw, resultType)) {
      //先查找相应的 TypeHandler 对象，再使用 TypeHandler 对象将该记录转换成 Java 类型的位
      return createPrimitiveResultObject(rsw, resultMap, columnPrefix);
    } else if (!constructorMappings.isEmpty()) {
      //2.ResultMap 中记录 constructor 节点的信息， 通过反射方式调用构造方法，创建结果对象
      return createParameterizedResultObject(rsw, resultType, constructorMappings, constructorArgTypes, constructorArgs, columnPrefix);
    } else if (resultType.isInterface() || metaType.hasDefaultConstructor()) {
      //3.使用默认的无参构造函数，则直接使用 ObjectFactory 创建对象
      return objectFactory.create(resultType);
    } else if (shouldApplyAutomaticMappings(resultMap, false)) {
      //4.通过自动映射的方式查找合适的构造方法并创建结果对象
      return createByConstructorSignature(rsw, resultType, constructorArgTypes, constructorArgs, columnPrefix);
    }
    throw new ExecutorException("Do not know how to create an instance of " + resultType);
  }

  Object createParameterizedResultObject(ResultSetWrapper rsw, Class<?> resultType, List<ResultMapping> constructorMappings,
                                         List<Class<?>> constructorArgTypes, List<Object> constructorArgs, String columnPrefix) {
    boolean foundValues = false;
    //遍历 constructorMappings 集合，该过程中会使用 constructorArgTypes 集合记录构造参数类型，使用 constructorArgs 集合记录构造函数实参
    for (ResultMapping constructorMapping : constructorMappings) {
      //获取当前构造参数的类型
      final Class<?> parameterType = constructorMapping.getJavaType();
      final String column = constructorMapping.getColumn();
      final Object value;
      try {
        if (constructorMapping.getNestedQueryId() != null) {
          //存在嵌套查询，需要处理该查询，然后才能得到实参，
          //在创建构造函数的参数时涉及的嵌套查询，无论配置如何，都不会延迟加载，会直接进行查询
          value = getNestedQueryConstructorValue(rsw.getResultSet(), constructorMapping, columnPrefix);
        } else if (constructorMapping.getNestedResultMapId() != null) {
          //存在嵌套查询，需妥处理该查询，然后才能得到实参，
          final ResultMap resultMap = configuration.getResultMap(constructorMapping.getNestedResultMapId());
          value = getRowValue(rsw, resultMap);
        } else {
          //直接获取该列的位，然后经过 TypeHandler 对象的转换，得到构造函数的实参
          final TypeHandler<?> typeHandler = constructorMapping.getTypeHandler();
          value = typeHandler.getResult(rsw.getResultSet(), prependPrefix(column, columnPrefix));
        }
      } catch (ResultMapException e) {
        throw new ExecutorException("Could not process result for mapping: " + constructorMapping, e);
      } catch (SQLException e) {
        throw new ExecutorException("Could not process result for mapping: " + constructorMapping, e);
      }
      constructorArgTypes.add(parameterType); //记录当前构造参数得类型
      constructorArgs.add(value); //记录当前构造参数得实际值
      foundValues = value != null || foundValues;
    }
    //通过 ObjectFactory 调用匹配的构造函数，创建结果对象
    return foundValues ? objectFactory.create(resultType, constructorArgTypes, constructorArgs) : null;
  }

  private Object createByConstructorSignature(ResultSetWrapper rsw, Class<?> resultType, List<Class<?>> constructorArgTypes, List<Object> constructorArgs,
                                              String columnPrefix) throws SQLException {
    final Constructor<?>[] constructors = resultType.getDeclaredConstructors();
    final Constructor<?> annotatedConstructor = findAnnotatedConstructor(constructors);
    if (annotatedConstructor != null) { //配置了注解 AutomapConstructor 的构造方法
      return createUsingConstructor(rsw, resultType, constructorArgTypes, constructorArgs, columnPrefix, annotatedConstructor);
    } else {
      for (Constructor<?> constructor : constructors) { //遍历所有构造器方法
        if (allowedConstructor(constructor, rsw.getClassNames())) { //找到合适的构造器
          //创建对象
          return createUsingConstructor(rsw, resultType, constructorArgTypes, constructorArgs, columnPrefix, constructor);
        }
      }
    }
    throw new ExecutorException("No constructor found in " + resultType.getName() + " matching " + rsw.getClassNames());
  }

  private Object createUsingConstructor(ResultSetWrapper rsw, Class<?> resultType, List<Class<?>> constructorArgTypes, List<Object> constructorArgs, String columnPrefix, Constructor<?> constructor) throws SQLException {
    boolean foundValues = false;
    for (int i = 0; i < constructor.getParameterTypes().length; i++) { //遍历构造器参数
      //获取参数类型
      Class<?> parameterType = constructor.getParameterTypes()[i];
      //获取 ResultSet 中的列名
      String columnName = rsw.getColumnNames().get(i);
      //查找对应的 TypeHandler ，并获取该列的位
      TypeHandler<?> typeHandler = rsw.getTypeHandler(parameterType, columnName);
      Object value = typeHandler.getResult(rsw.getResultSet(), prependPrefix(columnName, columnPrefix));
      //记录构造函数的参数类型和参数值
      constructorArgTypes.add(parameterType);
      constructorArgs.add(value);
      foundValues = value != null || foundValues;
    }
    //使用 ObjectFactory 调用对应的构造方法 建结采对象
    return foundValues ? objectFactory.create(resultType, constructorArgTypes, constructorArgs) : null;
  }

  private Constructor<?> findAnnotatedConstructor(final Constructor<?>[] constructors) {
    for (final Constructor<?> constructor : constructors) {
      if (constructor.isAnnotationPresent(AutomapConstructor.class)) {
        return constructor;
      }
    }
    return null;
  }

  private boolean allowedConstructor(final Constructor<?> constructor, final List<String> classNames) {
    final Class<?>[] parameterTypes = constructor.getParameterTypes();
    if (typeNames(parameterTypes).equals(classNames)) return true;
    if (parameterTypes.length != classNames.size()) return false;
    for (int i = 0; i < parameterTypes.length; i++) {
      final Class<?> parameterType = parameterTypes[i];
      if (parameterType.isPrimitive() && !primitiveTypes.getWrapper(parameterType).getName().equals(classNames.get(i))) {
        return false;
      } else if (!parameterType.isPrimitive() && !parameterType.getName().equals(classNames.get(i))) {
        return false;
      }
    }
    return true;
  }

  private List<String> typeNames(Class<?>[] parameterTypes) {
    List<String> names = new ArrayList<String>();
    for (Class<?> type : parameterTypes) {
      names.add(type.getName());
    }
    return names;
  }

  private Object createPrimitiveResultObject(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix) throws SQLException {
    final Class<?> resultType = resultMap.getType();
    final String columnName;
    if (!resultMap.getResultMappings().isEmpty()) {
      final List<ResultMapping> resultMappingList = resultMap.getResultMappings();
      final ResultMapping mapping = resultMappingList.get(0);
      columnName = prependPrefix(mapping.getColumn(), columnPrefix);
    } else {
      columnName = rsw.getColumnNames().get(0);
    }
    final TypeHandler<?> typeHandler = rsw.getTypeHandler(resultType, columnName);
    return typeHandler.getResult(rsw.getResultSet(), columnName);
  }

  //
  // NESTED QUERY
  //

  private Object getNestedQueryConstructorValue(ResultSet rs, ResultMapping constructorMapping, String columnPrefix) throws SQLException {
    // 获取嵌套查询的 id 以及对应 MappedStatement 对象
    final String nestedQueryId = constructorMapping.getNestedQueryId();
    final MappedStatement nestedQuery = configuration.getMappedStatement(nestedQueryId);
    final Class<?> nestedQueryParameterType = nestedQuery.getParameterMap().getType();
    //获取传递给嵌套查询的参数值
    final Object nestedQueryParameterObject = prepareParameterForNestedQuery(rs, constructorMapping, nestedQueryParameterType, columnPrefix);
    Object value = null;
    if (nestedQueryParameterObject != null) {
      //获取嵌套查询对应的 BoundSql 对象和相应的 CacheKey 对象
      final BoundSql nestedBoundSql = nestedQuery.getBoundSql(nestedQueryParameterObject);
      final CacheKey key = executor.createCacheKey(nestedQuery, nestedQueryParameterObject, RowBounds.DEFAULT, nestedBoundSql);
      //获取嵌套查询结采集经过映射后的目标类型
      final Class<?> targetType = constructorMapping.getJavaType();
      //创建 ResultLoader 对象，并调用 loadResult 方法执行嵌套查询，得到相应的构造方法参数值
      final ResultLoader resultLoader = new ResultLoader(configuration, executor, nestedQuery, nestedQueryParameterObject, targetType, key, nestedBoundSql);
      value = resultLoader.loadResult();
    }
    return value;
  }

  private Object getNestedQueryMappingValue(ResultSet rs, MetaObject metaResultObject, ResultMapping propertyMapping, ResultLoaderMap lazyLoader, String columnPrefix)
      throws SQLException {
    //获取嵌套查询的 id 和对应的 MappedStatement 对象
    final String nestedQueryId = propertyMapping.getNestedQueryId();
    final String property = propertyMapping.getProperty();
    final MappedStatement nestedQuery = configuration.getMappedStatement(nestedQueryId);
    //获取传递给嵌套查询的参数类型和参数值
    final Class<?> nestedQueryParameterType = nestedQuery.getParameterMap().getType();
    final Object nestedQueryParameterObject = prepareParameterForNestedQuery(rs, propertyMapping, nestedQueryParameterType, columnPrefix);
    Object value = null;
    if (nestedQueryParameterObject != null) { //参数不为null
      //获取嵌套查 对应 BoundSql 对象和相应 CacheKey 对象
      final BoundSql nestedBoundSql = nestedQuery.getBoundSql(nestedQueryParameterObject);
      final CacheKey key = executor.createCacheKey(nestedQuery, nestedQueryParameterObject, RowBounds.DEFAULT, nestedBoundSql);
      //获取嵌套查询结果集经过映射后的目标类型
      final Class<?> targetType = propertyMapping.getJavaType();
      //检测缓存中是否存在该嵌套查询的结采对象
      if (executor.isCached(nestedQuery, key)) {
        //创建 DeferredLoad 对象，并通过该 DeferredLoad 对象从缓存中加载结果对象
        executor.deferLoad(nestedQuery, metaResultObject, property, key, targetType);
        value = DEFERED; //返回 DEFERED 标识（是一个特殊的标识对象）
      } else {
        //没有命中缓存，则创建嵌套查询相应的 ResultLoader 对象
        final ResultLoader resultLoader = new ResultLoader(configuration, executor, nestedQuery, nestedQueryParameterObject, targetType, key, nestedBoundSql);
        if (propertyMapping.isLazy()) {
          //如采该属性配置了延迟加载，则将其添加到 ResultLoaderMap 中，等待真正使用时再执行嵌套查询并得到结采对象
          lazyLoader.addLoader(property, metaResultObject, resultLoader);
          value = DEFERED;
        } else {
          //没又配置延迟则直接调用 ResultLoader.loadResult 方法执行嵌套查询 ，并映射得到结果对象
          value = resultLoader.loadResult();
        }
      }
    }
    return value;
  }

  private Object prepareParameterForNestedQuery(ResultSet rs, ResultMapping resultMapping, Class<?> parameterType, String columnPrefix) throws SQLException {
    if (resultMapping.isCompositeResult()) {
      return prepareCompositeKeyParameter(rs, resultMapping, parameterType, columnPrefix);
    } else {
      return prepareSimpleKeyParameter(rs, resultMapping, parameterType, columnPrefix);
    }
  }

  private Object prepareSimpleKeyParameter(ResultSet rs, ResultMapping resultMapping, Class<?> parameterType, String columnPrefix) throws SQLException {
    final TypeHandler<?> typeHandler;
    if (typeHandlerRegistry.hasTypeHandler(parameterType)) {
      typeHandler = typeHandlerRegistry.getTypeHandler(parameterType);
    } else {
      typeHandler = typeHandlerRegistry.getUnknownTypeHandler();
    }
    return typeHandler.getResult(rs, prependPrefix(resultMapping.getColumn(), columnPrefix));
  }

  private Object prepareCompositeKeyParameter(ResultSet rs, ResultMapping resultMapping, Class<?> parameterType, String columnPrefix) throws SQLException {
    final Object parameterObject = instantiateParameterObject(parameterType);
    final MetaObject metaObject = configuration.newMetaObject(parameterObject);
    boolean foundValues = false;
    for (ResultMapping innerResultMapping : resultMapping.getComposites()) {
      final Class<?> propType = metaObject.getSetterType(innerResultMapping.getProperty());
      final TypeHandler<?> typeHandler = typeHandlerRegistry.getTypeHandler(propType);
      final Object propValue = typeHandler.getResult(rs, prependPrefix(innerResultMapping.getColumn(), columnPrefix));
      // issue #353 & #560 do not execute nested query if key is null
      if (propValue != null) {
        metaObject.setValue(innerResultMapping.getProperty(), propValue);
        foundValues = true;
      }
    }
    return foundValues ? parameterObject : null;
  }

  private Object instantiateParameterObject(Class<?> parameterType) {
    if (parameterType == null) {
      return new HashMap<Object, Object>();
    } else if (ParamMap.class.equals(parameterType)) {
      return new HashMap<Object, Object>(); // issue #649
    } else {
      return objectFactory.create(parameterType);
    }
  }

  //
  // DISCRIMINATOR
  //

  public ResultMap resolveDiscriminatedResultMap(ResultSet rs, ResultMap resultMap, String columnPrefix) throws SQLException {
    //记录已经处理过的 ResultMap的id
    Set<String> pastDiscriminators = new HashSet<String>();
    //获取 ResultMap 中的 Discriminator 对象。前面的构造过程也介绍过， discriminator ＞节点对应生
    //成的是 Discriminator 对象并记录到 ResultMap .discriminator 字段中，而不是生成 ResultMapping对象
    Discriminator discriminator = resultMap.getDiscriminator();
    while (discriminator != null) {
      //获取记录中对应列的值，其中会使用相应的 TypeHandler 对象将该列佳转换成 Java 类型
      final Object value = getDiscriminatorValue(rs, discriminator, columnPrefix);
      //根据该如 值获取对应的 ResultMap 的 id
      final String discriminatedMapId = discriminator.getMapIdFor(String.valueOf(value));
      if (configuration.hasResultMap(discriminatedMapId)) {
        //根据上述步骤获取的 id ，查找相应的 ResultMap 对象
        resultMap = configuration.getResultMap(discriminatedMapId);
        //记录当前 Discriminator 对象
        Discriminator lastDiscriminator = discriminator;
        //获取 ResultMap 对象中的 Discriminator
        discriminator = resultMap.getDiscriminator();
        //检测 Discriminator 是否 出现了循环引用
        if (discriminator == lastDiscriminator || !pastDiscriminators.add(discriminatedMapId)) {
          break;
        }
      } else {
        break;
      }
    }
    return resultMap; //该 ResultMap 对象为映射最终使用的 ResultMap
  }

  private Object getDiscriminatorValue(ResultSet rs, Discriminator discriminator, String columnPrefix) throws SQLException {
    final ResultMapping resultMapping = discriminator.getResultMapping();
    final TypeHandler<?> typeHandler = resultMapping.getTypeHandler();
    return typeHandler.getResult(rs, prependPrefix(resultMapping.getColumn(), columnPrefix));
  }

  private String prependPrefix(String columnName, String prefix) {
    if (columnName == null || columnName.length() == 0 || prefix == null || prefix.length() == 0) {
      return columnName;
    }
    return prefix + columnName;
  }

  //
  // HANDLE NESTED RESULT MAPS
  //

  private void handleRowValuesForNestedResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
    final DefaultResultContext<Object> resultContext = new DefaultResultContext<Object>();
    //步骤 1：定位到指定的记录行
    skipRows(rsw.getResultSet(), rowBounds);
    Object rowValue = previousRowValue;
    //步骤 2：检测是否能继续映射结采集中剩余的记录行
    while (shouldProcessMoreRows(resultContext, rowBounds) && rsw.getResultSet().next()) {
      //步骤 3：通过 resolveDiscriminatedResultMap （）方法决定映射使用的 ResultMap 对象
      final ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rsw.getResultSet(), resultMap, null);
      //步骤 4：为该行记录生成 CacheKey
      final CacheKey rowKey = createRowKey(discriminatedResultMap, rsw, null);
      //步骤 5：根据步骤 中生成的 CacheKey 查找 nestedResultObjects 集合
      Object partialObject = nestedResultObjects.get(rowKey);
      // issue #577 && #542
      if (mappedStatement.isResultOrdered()) { //步骤 6：检测 resultOrdered 属性
        if (partialObject == null && rowValue != null) { //主结果对象发生变化，(第一次进来rowValue为null)
          nestedResultObjects.clear(); //／清空 nestedResultObjects 集合
          //调用 storeObject 方法保存主结果对象（也就是嵌套映射的外层结果对象）
          storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
        }
        //步骤 7：完成该行记录的映射返回结果对象，其中还会将结采对象添加到 nestedResultObjects 集合中
        rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, null, partialObject);
      } else {
        ////步骤 7：完成该行记录的映射返回结果对象，其中还会将结采对象添加到 nestedResultObjects 集合中
        rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, null, partialObject);
        if (partialObject == null) { //步骤 8：调用 storeObject 方法保存结果对象
          storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
        }
      }
    }
    // resultOrdered 属性为 true 时的特殊处理，调用 storeObject 方法保存结果对象
    if (rowValue != null && mappedStatement.isResultOrdered() && shouldProcessMoreRows(resultContext, rowBounds)) {
      storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
      previousRowValue = null;
    } else if (rowValue != null) {
      previousRowValue = rowValue;
    }
  }

  //
  // GET VALUE FROM ROW FOR NESTED RESULT MAP
  //

  private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap, CacheKey combinedKey, String columnPrefix, Object partialObject) throws SQLException {
    final String resultMapId = resultMap.getId();
    Object rowValue = partialObject;
    if (rowValue != null) { //步骤 1: 检测外层对象是否已经存在
      final MetaObject metaObject = configuration.newMetaObject(rowValue);
      //步骤 3.1 ：将外层对象添加到 ancestorObjects 集合中
      putAncestor(rowValue, resultMapId);
      //步骤 3.2 ：处理嵌套映射
      applyNestedResultMappings(rsw, resultMap, metaObject, columnPrefix, combinedKey, false);
      //步骤 3.3：将外层对象从 ancestorObjects 集合中移除
      ancestorObjects.remove(resultMapId);
    } else {
      final ResultLoaderMap lazyLoader = new ResultLoaderMap(); //延迟加载
      //步骤 2.1 ：创 建外层对象
      rowValue = createResultObject(rsw, resultMap, lazyLoader, columnPrefix);
      if (rowValue != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
        final MetaObject metaObject = configuration.newMetaObject(rowValue);
        //更新 foundValues ，其含义与简单映射中同名变量相同：成功映射任意属性，则 foundValues 为 true, 否则为false
        boolean foundValues = this.useConstructorMappings;
        if (shouldApplyAutomaticMappings(resultMap, true)) { //步骤 2.2 ：自动映射
          foundValues = applyAutomaticMappings(rsw, resultMap, metaObject, columnPrefix) || foundValues;
        }
        //步骤 2.3：映射 ResultMap 中明确指定的字段
        foundValues = applyPropertyMappings(rsw, resultMap, metaObject, lazyLoader, columnPrefix) || foundValues;
        //步骤 2.4 ：将外层对象添加到 ancestorObjects 集合中
        putAncestor(rowValue, resultMapId);
        //步骤 2.5：处理嵌套映射
        foundValues = applyNestedResultMappings(rsw, resultMap, metaObject, columnPrefix, combinedKey, true) || foundValues;
        //步骤 2.6：将外层对象从 ancestorObjects 集合中移除
        ancestorObjects.remove(resultMapId);
        foundValues = lazyLoader.size() > 0 || foundValues;
        rowValue = foundValues || configuration.isReturnInstanceForEmptyRow() ? rowValue : null;
      }
      //步骤 2.7 ：将外层对象保存到 estedResultOb ects 合中，待映射后续记录时使用
      if (combinedKey != CacheKey.NULL_CACHE_KEY) {
        nestedResultObjects.put(combinedKey, rowValue);
      }
    }
    return rowValue;
  }

  private void putAncestor(Object resultObject, String resultMapId) {
    ancestorObjects.put(resultMapId, resultObject);
  }

  //
  // NESTED RESULT MAP (JOIN MAPPING)
  //

  private boolean applyNestedResultMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String parentPrefix, CacheKey parentRowKey, boolean newObject) {
    boolean foundValues = false;
    //遍历全部 ResultMapping 对象，处理其 中的嵌套映射
    for (ResultMapping resultMapping : resultMap.getPropertyResultMappings()) {
      //获取 ResultMapping.nestedResultMapId
      final String nestedResultMapId = resultMapping.getNestedResultMapId();
      //步骤 1.检测 nestedResultMapId 和 resultSet 两个字段的值
      if (nestedResultMapId != null && resultMapping.getResultSet() == null) {
        try {
          //获取列前缀
          final String columnPrefix = getColumnPrefix(parentPrefix, resultMapping);
          //步骤 2：确定嵌套映射使用的 ResultMap 对象
          final ResultMap nestedResultMap = getNestedResultMap(rsw.getResultSet(), nestedResultMapId, columnPrefix);
          //步骤 3：处理循环引用的情况
          if (resultMapping.getColumnPrefix() == null) {
            // try to fill circular reference only when columnPrefix
            // is not specified for the nested result map (issue #215)
            Object ancestorObject = ancestorObjects.get(nestedResultMapId);
            if (ancestorObject != null) {
              if (newObject) {
                linkObjects(metaObject, resultMapping, ancestorObject); // issue #385
              }
              // 若是循环引用，则不用执行下面的路径创建新对象，而是重用之前的对象
              continue;
            }
          }
          //步骤 4：为嵌套对象创建 CacheKey 对象
          final CacheKey rowKey = createRowKey(nestedResultMap, rsw, columnPrefix);
          final CacheKey combinedKey = combineKeys(rowKey, parentRowKey);
          //查找 nestedResultObjects 集合中是否有相同的 Key 的嵌套对象
          Object rowValue = nestedResultObjects.get(combinedKey);
          boolean knownValue = rowValue != null;
          //步骤 5：初始化外层对象中 Collection 类型的属性
          instantiateCollectionPropertyIfAppropriate(resultMapping, metaObject); // mandatory
          //步骤 6：根据 notNullColumn 属性检测结果集 中的空位
          if (anyNotNullColumnHasValue(resultMapping, columnPrefix, rsw)) {
            //步骤 7：完成嵌套映射，并生成嵌套对象
            rowValue = getRowValue(rsw, nestedResultMap, combinedKey, columnPrefix, rowValue);
            //注意，“!knownValue”这个条件，当嵌套对象已存在于 nestedResultObject 集合中时，
            // 说明相关列已经映射成了嵌套对象 ,现假设对象且中有 bl, b2 两个属性都指向了对象 B
            // 且这两个属性都是由同一 ResultMap 进行映射 在对一行记录进行映射时，
            // 首先映射的 bl 属性会生成 B对象且成功赋值，而 b2属性则为 null
            if (rowValue != null && !knownValue) {
              //步骤 8：将步骤 中得到的嵌套对象保存到外层对象的相应属性中
              linkObjects(metaObject, resultMapping, rowValue);
              foundValues = true;
            }
          }
        } catch (SQLException e) {
          throw new ExecutorException("Error getting nested result map values for '" + resultMapping.getProperty() + "'.  Cause: " + e, e);
        }
      }
    }
    return foundValues;
  }

  private String getColumnPrefix(String parentPrefix, ResultMapping resultMapping) {
    final StringBuilder columnPrefixBuilder = new StringBuilder();
    if (parentPrefix != null) {
      columnPrefixBuilder.append(parentPrefix);
    }
    if (resultMapping.getColumnPrefix() != null) {
      columnPrefixBuilder.append(resultMapping.getColumnPrefix());
    }
    return columnPrefixBuilder.length() == 0 ? null : columnPrefixBuilder.toString().toUpperCase(Locale.ENGLISH);
  }

  private boolean anyNotNullColumnHasValue(ResultMapping resultMapping, String columnPrefix, ResultSetWrapper rsw) throws SQLException {
    Set<String> notNullColumns = resultMapping.getNotNullColumns();
    if (notNullColumns != null && !notNullColumns.isEmpty()) {
      ResultSet rs = rsw.getResultSet();
      for (String column : notNullColumns) {
        rs.getObject(prependPrefix(column, columnPrefix));
        if (!rs.wasNull()) {
          return true;
        }
      }
      return false;
    } else if (columnPrefix != null) {
      for (String columnName : rsw.getColumnNames()) {
        if (columnName.toUpperCase().startsWith(columnPrefix.toUpperCase())) {
          return true;
        }
      }
      return false;
    }
    return true;
  }

  private ResultMap getNestedResultMap(ResultSet rs, String nestedResultMapId, String columnPrefix) throws SQLException {
    ResultMap nestedResultMap = configuration.getResultMap(nestedResultMapId);
    return resolveDiscriminatedResultMap(rs, nestedResultMap, columnPrefix);
  }

  //
  // UNIQUE RESULT KEY
  //

  /**
   * (1) 尝试使用＜idArg＞节点或＜id＞节点中中定义的列名以及该列在当前记录行中对应的列值
   * 组成 CacheKey 对象
   * (2)如果 ResultMap 中没有定义＜idArg＞节点或＜id>节点，则由 ResultMap 中明确要映射
   * 的列以及它们在当前记录行中对应的列值一起构成 CacheKey 对象
   * (3) 如果经过上述两个步骤后，依然查找不到相关的列名和列值，且 ResultMap 属性
   * 明确指明了结果对象为 Map 类型，则由结果集中所有列名以及该行记录行的所有列值一起构成CacheKey 对象
   * (4) 如果映射的结果对象不是 Map 类型 ，则由结果集中【未映射】的列名以及它在当前记
   * 录行中的对应列值一起构成 CacheKey 对象
   * @param resultMap
   * @param rsw
   * @param columnPrefix
   * @return
   * @throws SQLException
   */
  private CacheKey createRowKey(ResultMap resultMap, ResultSetWrapper rsw, String columnPrefix) throws SQLException {
    final CacheKey cacheKey = new CacheKey();
    cacheKey.update(resultMap.getId()); //将 ResultMap 的ID作为 CacheKey 的一部分
    List<ResultMapping> resultMappings = getResultMappingsForRowKey(resultMap); //查找 ResultMapping 对象集合
    if (resultMappings.isEmpty()) {//没有找到任何 ResultMapping
      if (Map.class.isAssignableFrom(resultMap.getType())) {
        //由结果集中的所有列名以及当前记录行的所有列值一起构成 CacheKey 对象
        createRowKeyForMap(rsw, cacheKey);
      } else {
        //由结果集中未映射的列名以及它们在当前记录 中的对应列位一起构成 CacheKey 对象
        createRowKeyForUnmappedProperties(resultMap, rsw, cacheKey, columnPrefix);
      }
    } else { //由 resultMappings 集合中的列名以及它们在当前记录行中相应得列值一起构成 CacheKey
      createRowKeyForMappedProperties(resultMap, rsw, cacheKey, resultMappings, columnPrefix);
    }
    if (cacheKey.getUpdateCount() < 2) {
      //如果通过上面的查找没有找到任何列参与 构成 CacheKey 对象，则返会 NullCacheKey 对象
      return CacheKey.NULL_CACHE_KEY;
    }
    return cacheKey;
  }

  private CacheKey combineKeys(CacheKey rowKey, CacheKey parentRowKey) {
    if (rowKey.getUpdateCount() > 1 && parentRowKey.getUpdateCount() > 1) {
      CacheKey combinedKey;
      try {
        combinedKey = rowKey.clone();
      } catch (CloneNotSupportedException e) {
        throw new ExecutorException("Error cloning cache key.  Cause: " + e, e);
      }
      //与外层对象的 CacheKey 合并，形成嵌套对象最终的 CacheKey
      combinedKey.update(parentRowKey);
      return combinedKey;
    }
    return CacheKey.NULL_CACHE_KEY;
  }

  private List<ResultMapping> getResultMappingsForRowKey(ResultMap resultMap) {
    //ResultMap.idResultMappings 集合中记录 id和ArgId 节点对应的 ResultMapping 对象
    List<ResultMapping> resultMappings = resultMap.getIdResultMappings();
    if (resultMappings.isEmpty()) {
      //ResultMap.propertyResultMappings 集合记录了除 <id＊> 节点之外的 ResultMapping 对象
      resultMappings = resultMap.getPropertyResultMappings();
    }
    return resultMappings;
  }

  private void createRowKeyForMappedProperties(ResultMap resultMap, ResultSetWrapper rsw, CacheKey cacheKey, List<ResultMapping> resultMappings, String columnPrefix) throws SQLException {
    for (ResultMapping resultMapping : resultMappings) { //遥历所有 resultMappings 集合
      if (resultMapping.getNestedResultMapId() != null && resultMapping.getResultSet() == null) {
        // Issue #392
        //如果存在嵌套映射， 递归调用 createRowKeyForMappedProperties 方法进行处理
        final ResultMap nestedResultMap = configuration.getResultMap(resultMapping.getNestedResultMapId());
        createRowKeyForMappedProperties(nestedResultMap, rsw, cacheKey, nestedResultMap.getConstructorResultMappings(),
            prependPrefix(resultMapping.getColumnPrefix(), columnPrefix));
      } else if (resultMapping.getNestedQueryId() == null) {
        //获取该列名称
        final String column = prependPrefix(resultMapping.getColumn(), columnPrefix);
        //获取该列相应的TypeHandler对象
        final TypeHandler<?> th = resultMapping.getTypeHandler();
        List<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix);
        // Issue #114
        if (column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH))) {
          //获取列对应的值
          final Object value = th.getResult(rsw.getResultSet(), column);
          if (value != null || configuration.isReturnInstanceForEmptyRow()) {
            //将列名和列值添加到CacheKey对象中
            cacheKey.update(column);
            cacheKey.update(value);
          }
        }
      }
    }
  }

  private void createRowKeyForUnmappedProperties(ResultMap resultMap, ResultSetWrapper rsw, CacheKey cacheKey, String columnPrefix) throws SQLException {
    final MetaClass metaType = MetaClass.forClass(resultMap.getType(), reflectorFactory);
    List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
    for (String column : unmappedColumnNames) {
      String property = column;
      if (columnPrefix != null && !columnPrefix.isEmpty()) {
        // When columnPrefix is specified, ignore columns without the prefix.
        if (column.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
          property = column.substring(columnPrefix.length());
        } else {
          continue;
        }
      }
      if (metaType.findProperty(property, configuration.isMapUnderscoreToCamelCase()) != null) {
        String value = rsw.getResultSet().getString(column);
        if (value != null) {
          cacheKey.update(column);
          cacheKey.update(value);
        }
      }
    }
  }

  private void createRowKeyForMap(ResultSetWrapper rsw, CacheKey cacheKey) throws SQLException {
    List<String> columnNames = rsw.getColumnNames();
    for (String columnName : columnNames) {
      final String value = rsw.getResultSet().getString(columnName);
      if (value != null) {
        cacheKey.update(columnName);
        cacheKey.update(value);
      }
    }
  }

  // 集合与非集合的处理逻辑对外封装在一起,这样便于用户使用,
  // 内部通过判断resultMapping中的类型确定是否为集合类型。
  // 无论是否为集合类型，最后都添加到parent的metaObject所封装的原始Object对应的属性上
  private void linkObjects(MetaObject metaObject, ResultMapping resultMapping, Object rowValue) {
    final Object collectionProperty = instantiateCollectionPropertyIfAppropriate(resultMapping, metaObject);
    if (collectionProperty != null) { //非空代表属性是集合类型
      final MetaObject targetMetaObject = configuration.newMetaObject(collectionProperty);
      targetMetaObject.add(rowValue);
    } else {
      metaObject.setValue(resultMapping.getProperty(), rowValue);
    }
  }
  //appropriate：adj. 适当的, 恰当的 / vt. 挪用; 占用; 盗用 / 拨出(款项)
  private Object instantiateCollectionPropertyIfAppropriate(ResultMapping resultMapping, MetaObject metaObject) {
    //获取指定的属性名称和当前属性值
    final String propertyName = resultMapping.getProperty();
    Object propertyValue = metaObject.getValue(propertyName);
    if (propertyValue == null) {//检测该属性是否已初始化
      Class<?> type = resultMapping.getJavaType(); //获取属性的 Java 类型
      if (type == null) {
        type = metaObject.getSetterType(propertyName);
      }
      try {
        if (objectFactory.isCollection(type)) {//指定属性为集合类型
          //通过 ObjectFactory 创建该类型的集合对象并进行相应设置
          propertyValue = objectFactory.create(type);
          metaObject.setValue(propertyName, propertyValue);
          return propertyValue;
        }
      } catch (Exception e) {
        throw new ExecutorException("Error instantiating collection property for result '" + resultMapping.getProperty() + "'.  Cause: " + e, e);
      }
    } else if (objectFactory.isCollection(propertyValue.getClass())) {//指定属性是集合类型且已经初始化，则返回该属性位
      return propertyValue;
    }
    return null;
  }

  private boolean hasTypeHandlerForResultObject(ResultSetWrapper rsw, Class<?> resultType) {
    if (rsw.getColumnNames().size() == 1) {
      return typeHandlerRegistry.hasTypeHandler(resultType, rsw.getJdbcType(rsw.getColumnNames().get(0)));
    }
    return typeHandlerRegistry.hasTypeHandler(resultType);
  }

}
